package com.gitee.zw.irmp.common.auth;

import com.gitee.zw.irmp.common.auth.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
public class AuthUtils {
    private static AuthUserHolder authUserHolder;
    public static class AuthUserHolder {
        public LoginUser getLoginUser() {
            if (RequestContextHolder.getRequestAttributes() == null) {
                return null;
            }
            LoginUser loginUser = (LoginUser) RequestContextHolder.getRequestAttributes().getAttribute(LOGIN_USER_PARM, RequestAttributes.SCOPE_REQUEST);
            return  loginUser;
        }
        public void setLoginUser(LoginUser loginUser) {
            RequestContextHolder.getRequestAttributes().setAttribute(LOGIN_USER_PARM, loginUser, RequestAttributes.SCOPE_REQUEST);
        }
        public String getLoginUsername() {
            LoginUser user = getLoginUser();
            return user == null ? null : user.getUsername();
        }
    }

    public static AuthUserHolder init(AuthUserHolder authUserHolder) {
        AuthUtils.authUserHolder = authUserHolder;
        return authUserHolder;
    }

    public static AuthUserHolder init() {
        if (AuthUtils.authUserHolder == null) {
            AuthUtils.authUserHolder = new AuthUserHolder();
        }
        return authUserHolder;
    }

    public static final String LOGIN_USER_PARM = "loginUser";

    public static LoginUser getLoginUser() {
        LoginUser loginUser = authUserHolder.getLoginUser();
        return  loginUser;
    }
    public static void setLoginUser(LoginUser loginUser) {
        authUserHolder.setLoginUser(loginUser);
    }
    public static String getLoginUsername() {

        return authUserHolder.getLoginUsername();
    }

    public static Boolean isAdmin() {
        Object res = getLoginUser().getRoles().stream().filter(role -> "SUPER_ADMIN".equals(role.getRoleCode())).findFirst().orElse(null);
        return res != null;
    }
}
